package com.zryc.shop.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class JwtUtils {
    public static final  long EXP = 15*60*1000L;//设置令牌的默认过期时间15min
    public static final  String ISS = "XXW";
    public static final  String SECRET_KEY ="xxw-yyds";//默认的密钥

    //生成jwt
    public static String generageJwt(String userId,String username,Long expMillis){
        long timeMillis=System.currentTimeMillis();
        JwtBuilder builder= Jwts.builder()
                .setId(UUID.randomUUID().toString())//设置Id(唯一标识)
                .setSubject("USER_AUTH_TOKEN")//设置主题
                .setIssuer(ISS)//设置签发人
                .setIssuedAt(new Date(timeMillis))//设置签发时间
                .claim("userId",userId)
                .claim("username",username)
                .signWith(SignatureAlgorithm.HS256,SECRET_KEY)//设置签名的算法和密钥
                .setExpiration(new Date(expMillis==null ? (timeMillis+EXP):(timeMillis + expMillis)));//设置令牌的过期时间
        return builder.compact();
    }

    //解析Jwt
    public static Claims parseJwt(String jwt) throws Exception{
        return Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(jwt)//解析带有签名的jws
                .getBody();
    }




    public static void main(String[] args) throws Exception {
//        System.out.println(generageJwt("0030","xujiajun",null));
    String claim="eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJlMjcwZTJjOS1iZTcxLTQyZWYtYjllOS02NDI0YmNhN2I4OTQiLCJzdWIiOiJVU0VSX0FVVEhfVE9LRU4iLCJpc3MiOiJYWFciLCJpYXQiOjE2NjcwMTUyNzYsInVzZXJJZCI6IjAwMzAiLCJ1c2VybmFtZSI6Inh1amlhanVuIiwiZXhwIjoxNjY3MDE2MTc2fQ.XnCZzCsY9D0-K8v3dzNMa8KEEwNNhyfC1gvN4pstTs8";
        System.out.println(parseJwt(claim));
    }




}
